<?php
// 企业微信推送接口
// 调用方式：push.php?title=标题&content=内容

// 配置区域
$config = [
    // 企业微信机器人Webhook Key
    'QYWX_KEY' => '5d77353c-b7fa-45dd-bfbc-cd88a0862697',
    
    // 企业微信应用配置 (企业ID,应用AgentId,应用Secret,类型)
    'QYWX_AM' => [
        [
            'corpId' => 'ww6223f231c4b96152',
            'agentId' => '1000002',
            'secret' => 'RktCg_VCIjxJmF1aPyEGDMt2qUVoL1QJlRi1yZob6WM',
            'type' => 'yy' // yy:应用消息 jx:家校消息
        ]
    ],
    
    // 访问令牌 (用于简单身份验证)
    'API_TOKEN' => 'yinghuochong',
    
    // 缓存目录 (确保有写入权限)
    'CACHE_DIR' => __DIR__ . '/cache'
];

// 创建缓存目录
if (!file_exists($config['CACHE_DIR'])) {
    mkdir($config['CACHE_DIR'], 0777, true);
}

// 获取请求参数
$title = $_GET['title'] ?? '';
$content = $_GET['content'] ?? '';
$token = $_GET['token'] ?? '';

// 验证参数
if (empty($title) || empty($content)) {
    die(json_encode(['code' => 400, 'msg' => '标题和内容不能为空']));
}

if ($token !== $config['API_TOKEN']) {
    die(json_encode(['code' => 403, 'msg' => '无效的访问令牌']));
}

// 组合消息内容
$message = "【{$title}】\n\n{$content}";

// 执行推送
$results = [];
$results['qywx_bot'] = sendQYWXBot($config['QYWX_KEY'], $message);
$results['qywx_app'] = sendQYWXApp($config['QYWX_AM'], $message, $config['CACHE_DIR']);

// 返回结果
echo json_encode([
    'code' => 200,
    'msg' => '推送请求已发送',
    'results' => $results
]);

/**
 * 发送企业微信机器人消息
 */
function sendQYWXBot($key, $message) {
    if (empty($key)) return ['success' => false, 'error' => '未配置机器人KEY'];
    
    $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={$key}";
    
    $data = [
        'msgtype' => 'text',
        'text' => ['content' => $message]
    ];
    
    return sendRequest($url, $data);
}

/**
 * 发送企业微信应用消息
 */
function sendQYWXApp($apps, $message, $cacheDir) {
    if (empty($apps)) return ['success' => false, 'error' => '未配置应用信息'];
    
    $results = [];
    foreach ($apps as $app) {
        // 获取Access Token
        $token = getAccessToken($app['corpId'], $app['secret'], $cacheDir);
        if (!$token) {
            $results[] = ['success' => false, 'error' => '获取Token失败'];
            continue;
        }
        
        // 确定API端点
        $endpoint = ($app['type'] === 'jx') ? 
            'cgi-bin/externalcontact/message/send' : 
            'cgi-bin/message/send';
        
        $url = "https://qyapi.weixin.qq.com/{$endpoint}?access_token={$token}";
        
        // 构建请求数据
        if ($app['type'] === 'jx') {
            $data = [
                'toall' => 1,
                'agentid' => $app['agentId'],
                'msgtype' => 'text',
                'text' => ['content' => $message],
                'enable_duplicate_check' => 1,
                'duplicate_check_interval' => 1800
            ];
        } else {
            $data = [
                'touser' => '@all',
                'agentid' => $app['agentId'],
                'msgtype' => 'text',
                'text' => ['content' => $message],
                'safe' => 0
            ];
        }
        
        $results[] = sendRequest($url, $data);
    }
    
    return $results;
}

/**
 * 获取Access Token (带缓存)
 */
function getAccessToken($corpId, $secret, $cacheDir) {
    $cacheFile = "{$cacheDir}/token_{$corpId}.json";
    $cacheLifetime = 7100; // 缓存有效时间(秒)
    
    // 尝试从缓存读取
    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && time() < $cache['expires_time']) {
            return $cache['access_token'];
        }
    }
    
    // 请求新Token
    $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpId}&corpsecret={$secret}";
    $response = sendRequest($url, [], 'GET');
    
    if (!$response['success'] || empty($response['data']['access_token'])) {
        error_log("获取Token失败: " . print_r($response, true));
        return false;
    }
    
    // 更新缓存
    $cacheData = [
        'access_token' => $response['data']['access_token'],
        'expires_time' => time() + $cacheLifetime
    ];
    
    file_put_contents($cacheFile, json_encode($cacheData));
    return $response['data']['access_token'];
}

/**
 * 发送HTTP请求 (修复SSL验证问题)
 */
function sendRequest($url, $data = [], $method = 'POST') {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    // 修复SSL证书问题
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    
    // 获取更多错误信息
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [
            'success' => false,
            'error' => "cURL错误: {$error}",
            'http_code' => $httpCode
        ];
    }
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // 处理非200响应
    if ($httpCode !== 200) {
        return [
            'success' => false,
            'error' => "HTTP错误: {$httpCode}",
            'response' => $response
        ];
    }
    
    $decoded = json_decode($response, true);
    return [
        'success' => true,
        'data' => $decoded,
        'raw' => $response
    ];
}